package cn.edu.zzu.demo03ThreadSecurity;

/**
 * 买票案例
 */
public class TestUnSecurity {

    public static void main(String[] args) {
        TicketSale ticketSale = new TicketSale();

        new Thread(ticketSale, "小红").start();
        new Thread(ticketSale, "小马").start();
        new Thread(ticketSale, "黄牛").start();
    }

}

class TicketSale implements Runnable {

    //票数
    private Integer ticketNum = 10;

    //标志
    private boolean flag = true;

    public TicketSale() {

    }

    public TicketSale(Integer ticketNum) {
        this.ticketNum = ticketNum;
    }

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //改进：将共享操作的方法进行互斥锁操作 synchronized
    public synchronized void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + " 买到了 " + ticketNum);
        ticketNum--;
        Thread.sleep(100);
    }
}
